import java.io.IOException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;

public class SoundThread extends Thread { 

	private String filename;
	private SourceDataLine auline;
	private Position curPosition;
	private double volume;
	private boolean stop = false;

	private final int EXTERNAL_BUFFER_SIZE = 524288; // 128Kb 

	enum Position { 
		LEFT, RIGHT, NORMAL
	};

	public SoundThread(String wavfile) { 
		filename = wavfile;
		curPosition = Position.NORMAL;
	} 

	public SoundThread(String wavfile, Position p) { 
		filename = wavfile;
		curPosition = p;
	} 

	public void setVolume(double a) {
		FloatControl gainControl = (FloatControl)auline.getControl(FloatControl.Type.MASTER_GAIN);
		volume = a;
		float dB = (float)(Math.log(volume)/Math.log(10.0)*20.0);
		gainControl.setValue(dB);
	}

	public void run() { 

		java.net.URL soundFile = getClass().getClassLoader().getResource("sounds/"+filename);

		AudioInputStream audioInputStream = null;
		try { 
			audioInputStream = AudioSystem.getAudioInputStream(soundFile);
		} catch (UnsupportedAudioFileException e1) { 
			e1.printStackTrace();
			return;
		} catch (IOException e1) { 
			e1.printStackTrace();
			return;
		} 

		AudioFormat format = audioInputStream.getFormat();
		auline = null;
		DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

		try { 
			auline = (SourceDataLine) AudioSystem.getLine(info);
			auline.open(format);
		} catch (LineUnavailableException e) { 
			e.printStackTrace();
			return;
		} catch (Exception e) { 
			e.printStackTrace();
			return;
		} 

		if (auline.isControlSupported(FloatControl.Type.PAN)) { 
			FloatControl pan = (FloatControl) auline
					.getControl(FloatControl.Type.PAN);
			if (curPosition == Position.RIGHT) 
				pan.setValue(1.0f);
			else if (curPosition == Position.LEFT) 
				pan.setValue(-1.0f);
		} 

		FloatControl gainControl = (FloatControl)auline.getControl(FloatControl.Type.MASTER_GAIN);
		float dB = (float)(Math.log(volume)/Math.log(10.0)*20.0);
		gainControl.setValue(dB);

		auline.start();
		int nBytesRead = 0;
		byte[] abData = new byte[EXTERNAL_BUFFER_SIZE];

		try { 
			while (nBytesRead != -1 && !this.stop) { 
				nBytesRead = audioInputStream.read(abData, 0, abData.length);
				if (nBytesRead >= 0) 
					auline.write(abData, 0, nBytesRead);
			} 
		} catch (IOException e) { 
			e.printStackTrace();
			return;
		} 

		auline.drain();
		auline.close();


	}

	public void kill(){
		this.stop = true;
	}

	public double getVolume() {
		return volume;
	}

	public void setDefaultVolume(double outputVolume) {
		volume = outputVolume;
	} 
} 